<template>
  <div
    :style="{ height: `${height}px` }"
    class="outer"
    ref="outer"
    @mouseover="stopScroll"
    @mouseleave="startScroll"
  >
    <div ref="inner1">
      <slot />
    </div>
    <div ref="inner2" />
  </div>
</template>

<script>
import { onMounted, onUnmounted, onUpdated, ref } from "vue";
export default {
  props: {
    // 设定容器高度
    height: {
      type: Number,
      default: 0,
    },
  },
  setup(prop, cxt) {
    let outer = ref(null);
    let inner1 = ref(null);
    let inner2 = ref(null);
    let autoScrollInterval = ref(null);
    onMounted(() => {
      tryScroll();
    });
    onUpdated(() => {
      tryScroll();
    });
    onUnmounted(() => {
      clearInterval(autoScrollInterval.value);
    });
    const tryScroll = () => {
      if (inner1.value.clientHeight > outer.value.clientHeight) {
        inner2.value.innerHTML = inner1.value.innerHTML;
        startScroll();
      } else {
        inner2.value.innerHTML = "";
        stopScroll();
      }
    };
    const startScroll = () => {
      if (!autoScrollInterval.value) {
        autoScrollInterval.value = setInterval(() => {
          if (outer.value.scrollTop >= inner1.value.offsetHeight) {
            outer.value.scrollTop = 0;
            cxt.emit("complete");
          } else {
            outer.value.scrollTop += 1;
            if (
              outer.value.scrollTop === Math.ceil(inner1.value.offsetHeight / 2)
            ) {
              cxt.emit("half");
            }
          }
        }, 50);
      }
    };
    const stopScroll = () => {
      clearInterval(autoScrollInterval.value);
      autoScrollInterval.value = null;
    };
    return {
      outer,
      inner1,
      inner2,
      tryScroll,
      autoScrollInterval,
      startScroll,
      stopScroll,
    };
  },
};
</script>

<style scoped>
.outer {
  overflow: hidden;
  position: absolute;
  bottom: 60px;
  padding: 0px 15px;
  animation: outerFly 3s ease-in-out alternate both;
}
@keyframes outerFly {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
</style>
